package com.pro01.backend.service;

import com.pro01.backend.mapper.ForumPostLikeMapper;
import com.pro01.backend.mapper.ForumPostMapper;
import com.pro01.backend.pojo.ForumPost;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ForumPostService {

    @Autowired
    private ForumPostMapper forumPostMapper;

    @Autowired
    private ForumPostLikeMapper forumPostLikeMapper;

    @Autowired
    private PointService pointService;

    // 发布帖子
    public void createPost(ForumPost post) {
        // 设置默认值
        post.setIsPinned(false);
        post.setStatus("ACTIVE");
        post.setViewCount(0);
        post.setCommentCount(0);
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());

        int result = forumPostMapper.insertPost(post);

        // 发帖加积分
        pointService.addPostReward(post.getUserId());
        if (result == 0) {
            throw new RuntimeException("发帖失败");
        }
    }

    // 用户查看所有帖子
//
    public PageResult<ForumPost> getPostsByForum(Long forumId, Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumPost> records = forumPostMapper.selectPostsByForum(forumId, offset, pageSize);
        int total = forumPostMapper.countPostsByForum(forumId);

        if (userId != null && !records.isEmpty()) {
            // 收集 postId 列表
            List<Long> postIds = records.stream().map(ForumPost::getId).toList();
            String postIdsStr = postIds.stream().map(String::valueOf).collect(Collectors.joining(","));

            // 查出当前用户点过赞的帖子ID
            List<Long> likedPostIds = forumPostLikeMapper.getLikedPostIds(userId, postIdsStr);

            // 遍历设置 hasLiked
            for (ForumPost post : records) {
                post.setHasLiked(likedPostIds.contains(post.getId()));
            }
        }

        return new PageResult<>(total, records);
    }


    // 用户查看帖子详情
//    public ForumPost getPostDetail(Long postId) {
//        ForumPost post = forumPostMapper.getPostById(postId);
//        if (post == null) {
//            throw new RuntimeException("帖子不存在或已被删除");
//        }
//
//        // 浏览量 +1
//        forumPostMapper.increaseViewCount(postId);
//
//        return post;
//    }
    public ForumPost getPostDetail(Long postId, Long userId) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        // 浏览量 +1
        forumPostMapper.increaseViewCount(postId);

        // 查询是否点赞
        boolean liked = forumPostLikeMapper.hasLiked(userId, postId) > 0;
        post.setHasLiked(liked);

        return post;
    }

    // 用户编辑帖子
    public void updatePost(Long postId, Long userId, String title, String content) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }
        if (!post.getUserId().equals(userId)) {
            throw new RuntimeException("无权限编辑他人帖子");
        }

        post.setId(postId);
        post.setTitle(title);
        post.setContent(content);
        int result = forumPostMapper.updatePost(post);
        if (result == 0) {
            throw new RuntimeException("帖子更新失败");
        }
    }

    // 用户删除帖子
    public void deletePost(Long postId, Long userId) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }
        if (!post.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除他人帖子");
        }

        int result = forumPostMapper.softDeletePost(postId);
        if (result == 0) {
            throw new RuntimeException("帖子删除失败");
        }
    }

    // 用户模糊查询帖子
    public PageResult<ForumPost> searchPostsByTitle(String title, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumPost> records = forumPostMapper.searchPostsByTitle(title, offset, pageSize);
        int total = forumPostMapper.countPostsByTitle(title);
        return new PageResult<>(total, records);
    }

    // 用户查看自己的所有帖子
    public PageResult<ForumPost> getPostsByUser(Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumPost> records = forumPostMapper.selectPostsByUser(userId, offset, pageSize);
        int total = forumPostMapper.countPostsByUser(userId);
        return new PageResult<>(total, records);
    }

    // 用户隐藏自己的帖子
    public void hidePostByUser(Long postId, Long userId) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }
        if (!post.getUserId().equals(userId)) {
            throw new RuntimeException("无权限隐藏他人的帖子");
        }
        if (!"ACTIVE".equals(post.getStatus())) {
            throw new RuntimeException("只有处于 ACTIVE 状态的帖子才能被隐藏");
        }

        int result = forumPostMapper.hidePostByUser(postId, userId);
        if (result == 0) {
            throw new RuntimeException("隐藏帖子失败");
        }
    }

    // 用户取消隐藏自己的帖子
    public void restorePostByUser(Long postId, Long userId) {
        ForumPost post = forumPostMapper.getHiddenPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }
        if (!post.getUserId().equals(userId)) {
            throw new RuntimeException("无权限恢复他人的帖子");
        }
        if (!"HIDDEN".equals(post.getStatus())) {
            throw new RuntimeException("只有处于 HIDDEN 状态的帖子才能恢复");
        }

        int result = forumPostMapper.restorePostByUser(postId, userId);
        if (result == 0) {
            throw new RuntimeException("恢复帖子失败");
        }
    }

    /**
     * 接下来是管理员的接口
     */

    // 查询当前板块下的所有帖子(仅限管理员)
    public PageResult<ForumPost> getPostsByForumForAdmin(Long forumId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumPost> records = forumPostMapper.selectPostsByForumForAdmin(forumId, offset, pageSize);
        int total = forumPostMapper.countPostsByForumForAdmin(forumId);
        return new PageResult<>(total, records);
    }

    // 删除帖子(仅限管理员)
    public void deletePostByAdmin(Long postId, Long forumId) {
        // 确认帖子存在
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        // 删除帖子（软删除）
        int result = forumPostMapper.deletePostByAdmin(postId, forumId);
        if (result == 0) {
            throw new RuntimeException("帖子删除失败");
        }
    }

    // 恢复已删除的帖子(仅限管理员)
    public void restorePost(Long postId, Long forumId) {
        // 获取帖子
        ForumPost post = forumPostMapper.getAllPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        // 检查帖子状态，如果是 'DELETED' 或 'HIDDEN'，则可以恢复
        if (!"DELETED".equals(post.getStatus()) && !"HIDDEN".equals(post.getStatus())) {
            throw new RuntimeException("该帖子无法恢复");
        }

        // 恢复帖子
        int result = forumPostMapper.restorePost(postId, forumId);
        if (result == 0) {
            throw new RuntimeException("恢复帖子失败");
        }
    }

    // 隐藏帖子(仅限管理员)
    public void hidePost(Long postId, Long forumId) {
        // 获取帖子
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }

        // 检查帖子是否是 'ACTIVE' 状态，只有 'ACTIVE' 的帖子才能被隐藏
        if (!"ACTIVE".equals(post.getStatus())) {
            throw new RuntimeException("该帖子无法隐藏");
        }

        // 隐藏帖子
        int result = forumPostMapper.hidePost(postId, forumId);
        if (result == 0) {
            throw new RuntimeException("隐藏帖子失败");
        }
    }

    // 置顶帖子(仅限管理员)
    public void pinPost(Long postId, Long forumId) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }

        int result = forumPostMapper.pinPost(postId, forumId);
        if (result == 0) {
            throw new RuntimeException("置顶帖子失败");
        }
    }

    // 取消置顶帖子(仅限管理员)
    public void unpinPost(Long postId, Long forumId) {
        ForumPost post = forumPostMapper.getPostById(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }

        int result = forumPostMapper.unpinPost(postId, forumId);
        if (result == 0) {
            throw new RuntimeException("取消置顶失败");
        }
    }


}
